<template>
    <div class="register-container">
        <div class="title">
            <h2>修改密码</h2>
            <p class="tip-text">为了您的账号安全，请定期更换密码</p>
        </div>
        <!-- 表单区域 -->
        <div class="form-container">
            <el-form ref="registerFormRules" :model="form" :rules="changerPwdRules" class="register-form">
                <el-form-item label="用户名/学号" prop="account">
                    <el-input v-model="form.account" placeholder="请输入账号"></el-input>
                </el-form-item>
                <el-form-item label="设置密码" prop="password">
                    <template #label>
                        <span>设置密码</span>
                    </template>
                    <el-input v-model="form.password" type="password" placeholder="请设置密码（至少8位，包含字母和数字）"></el-input>
                </el-form-item>
                <el-form-item label="" prop="" style="background-color: #eff6ff; border-radius: 10px;">
                    <div style="display: flex; align-items: center;gap: 10px; padding-left: 5px;">
                        <el-icon color="#165dff"><warning-filled /></el-icon>
                        <span>密码要求</span>
                    </div>
                    <ul style="padding:10px 25px;width: 100%;">
                        <li>长度至少8个字符</li>
                        <li>包含大小写字母、数字和特殊符号</li>
                        <li>不能与账号名相同</li>
                        <li>不能使用常见密码</li>
                    </ul>
                </el-form-item>

                <el-form-item label="确认密码" prop="confirmPassword">
                    <template #label>
                        <span>确认密码</span>
                    </template>
                    <el-input v-model="form.confirmPassword" type="password" placeholder="请再次输入密码"></el-input>
                </el-form-item>

                <el-form-item>
                    <el-button type="primary" @click.stop="handleChangerPwd"
                        style="width: 100%; color: white;margin: 10px 0;">确定修改</el-button>
                    <el-button type="default" style="width: 100%; margin-left: 0;">
                        <router-link to="/login">取消</router-link>
                    </el-button>
                </el-form-item>
            </el-form>
        </div>
    </div>
</template>

<script setup>
import { ref, reactive, watch } from 'vue';
import { ElForm, ElFormItem, ElInput, ElSelect, ElOption, ElCheckbox, ElLink, ElButton, ElMessage } from 'element-plus';
import { useRouter } from 'vue-router';
import { useWindowSize } from '@vueuse/core';
// 导入API
import {  resetPassword } from '@/api/user';
import { useStore } from "@/store";
const store = useStore();
const router = useRouter();
const { width } = useWindowSize();
const isMobile = ref(false);
const registerFormRules = ref(null)
// 根据窗口宽度判断是否为移动端，可自行调整阈值，比如 768px 以下视为移动端
watch(width, (val) => {
    isMobile.value = val < 768;
});

const form = reactive({
    account: '',
    pwd: '',
    confirmPassword: ''
});

let currentPwd = ref('')

const changerPwdRules = reactive({
    account: [
        { required: true, message: '请输入用户名/学号', trigger: 'blur' }
    ],
    password: [
        { required: true, message: '请设置密码', trigger: 'blur' },
        { pattern: /^(?=.*[a-zA-Z])(?=.*\d)[a-zA-Z\d]{8,}$/, message: '密码至少8位，包含字母和数字', trigger: 'blur' }
    ],
    confirmPassword: [
        { required: true, message: '请再次输入密码', trigger: 'blur' },
        {
            validator: (rule, value, callback) => {
                if (value !== form.password) {
                    callback(new Error('两次输入密码不一致'));
                } else {
                    callback();
                }
            }, trigger: 'blur'
        }
    ]
});



// 确定修改
const handleChangerPwd = () => {
    registerFormRules.value.validate(async (valid) => {
        if (valid) {
            // 调用API进行注册
            await resetPassword({
                oldpassword: currentPwd.value ,
                newpassword: form.password,
            }).then(res => {
                if (res.code > 0) {
                    ElMessage.success('修改密码成功，请去登录页'); // 这里可以添加注册成功的逻辑
                    sessionStorage.removeItem('token')
                    router.push('/login');
                    
                } else {
                    ElMessage.error(res.message || '修改失败');
                }
            }).catch(error => {
                ElMessage.error('网络错误，请重试');
            });
        }
    });
};


// 页面加载
onMounted(() => {
    const token = sessionStorage.getItem('token');
    if (token) {
      let { password }  = JSON.parse(token)
      console.log(password);
      
      currentPwd.value =  password
    }
});
</script>


<style scoped lang="scss">
.register-container {
    position: relative;
    max-width: 1420px;
    height: 80vh;
    margin: 0 auto;
    display: flex;
    justify-content: center;
    align-items: center;

    .form-container {
        width: 400px;
        padding: 20px;
        border-radius: 10px;
        box-shadow: 0 5px 5px rgba(0, 0, 0, 0.1);

        .el-form-item {
            display: flex;
            flex-direction: column;

            .el-input,
            .el-select {
                height: 40px;
            }

            ::v-deep .el-select .el-select__wrapper {
                height: 100%;
            }

            ::v-deep .el-form-item__content {
                justify-content: space-between;
            }
        }

        ::v-deep .el-form-item--label-right .el-form-item__label {
            width: auto;
            justify-content: flex-start;
            text-align: left;
        }

        h1 {
            text-align: center;
            margin-bottom: 20px;
        }
    }

    .title {
        position: absolute;
        top: 20px;
        left: 10px;

        p {
            color: #848b95;
            margin: 10px 0 0 0;
        }
    }
}



@media (max-width: 767px) {
    .right-section {
        width: 100%;

        .el-form-item {
            display: flex;
            flex-direction: column;
            margin-bottom: 8px;

            ::v-deep .el-form-item__content {
                justify-content: space-between;
            }
        }

        ::v-deep .el-form-item--label-right .el-form-item__label {
            width: auto;
            justify-content: flex-start;
            text-align: left;
        }
    }
}
</style>
